package org.jetlinks.community.mstn.web;

import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.hswebframework.reactor.excel.ReactorExcel;
import org.hswebframework.web.api.crud.entity.QueryNoPagingOperation;
import org.hswebframework.web.api.crud.entity.QueryParamEntity;
import org.hswebframework.web.authorization.annotation.Authorize;
import org.hswebframework.web.authorization.annotation.QueryAction;
import org.hswebframework.web.authorization.annotation.Resource;
import org.hswebframework.web.bean.FastBeanCopier;
import org.jetlinks.community.device.web.excel.DeviceExcelInfo;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Collections;

/**
 * @author zhengzuowei
 */
@RestController
@RequestMapping("/mstn/export")
@Authorize
@Resource(id = "export", name = "导出管理", group = "mstn")
@Tag(name = "导出管理")
@AllArgsConstructor
public class ExportController {
//    //直接导出数据,不支持导出标签.
//    @GetMapping("/export.{format}")
//    @QueryAction
//    @QueryNoPagingOperation(summary = "导出设备实例数据", description = "此操作不支持导出设备标签和配置信息")
//    public Mono<Void> export(ServerHttpResponse response,
//                             @Parameter(hidden = true) QueryParamEntity parameter,
//                             @PathVariable @Parameter(description = "文件格式,支持csv,xlsx") String format) throws IOException {
//        response.getHeaders().set(HttpHeaders.CONTENT_DISPOSITION,
//            "attachment; filename=".concat(URLEncoder.encode("设备实例." + format, StandardCharsets.UTF_8
//                .displayName())));
//        return ReactorExcel.<DeviceExcelInfo>writer(format)
//            .headers(DeviceExcelInfo.getExportHeaderMapping(Collections.emptyList(), Collections.emptyList()))
//            .converter(DeviceExcelInfo::toMap)
//            .writeBuffer(
//                service
//                    .query(parameter)
//                    .map(entity -> {
//                        DeviceExcelInfo exportEntity = FastBeanCopier.copy(entity, new DeviceExcelInfo(), "state");
//                        exportEntity.setState(entity.getState().getText());
//                        return exportEntity;
//                    })
//                , 512 * 1024)//缓冲512k
//            .doOnError(err -> log.error(err.getMessage(), err))
//            .map(bufferFactory::wrap)
//            .as(response::writeWith);
//    }
}
